
jsColorPicker = function (container, callback) {
  var container = container;
  return new _jsColorPicker(container, callback)
}

_jsColorPicker = function (container, callback) {
  // Store farbtastic object
  var self = this;  

  // Insert markup
  container.innerHTML = '<div class="color-picker-container"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>';
  self.wheel = document.querySelector('.wheel');
  // Dimensions
  self.radius = 84;
  self.square = 100;
  self.width = 194;

  /**
   * Link to the given element(s) or callback.
   */
  self.linkTo = function (callback) {
    // Unbind previous nodes
    if (typeof self.callback == 'object') {
      document.querySelectorAll(self.callback)[0].removeEventListener('keyup', self.updateValue);
    }

    // Reset color
    self.color = null;

    // Bind callback or elements
    if (typeof callback == 'function') {
      self.callback = callback;
    }
    else if (typeof callback == 'object' || typeof callback == 'string') {
      self.callback = document.querySelectorAll(callback)[0];
      self.callback.addEventListener('keyup', self.updateValue);
      if (self.callback.value) {
        self.setColor(self.callback.value);
      }
    }
    return this;
  }
  self.updateValue = function (event) {
    if (this.value && this.value != self.color) {
      self.setColor(this.value);
    }
  }

  /**
   * Change color with HTML syntax #123456
   */
  self.setColor = function (color) {
    var unpack = self.unpack(color);
    if (self.color != color && unpack) {
      self.color = color;
      self.rgb = unpack;
      self.hsl = self.RGBToHSL(self.rgb);
      self.updateDisplay();
    }
    return this;
  }

  /**
   * Change color with HSL triplet [0..1, 0..1, 0..1]
   */
  self.setHSL = function (hsl) {
    self.hsl = hsl;
    self.rgb = self.HSLToRGB(hsl);
    self.color = self.pack(self.rgb);
    self.updateDisplay();
    return this;
  }

  /////////////////////////////////////////////////////

  /**
   * Retrieve the coordinates of the given event relative to the center
   * of the widget.
   */
  self.widgetCoords = function (event) {
    var x, y;
    var el = event.target || event.srcElement;
    var reference = self.wheel;

    if (typeof event.offsetX != 'undefined') {
      // Use offset coordinates and find common offsetParent
      var pos = { x: event.offsetX, y: event.offsetY };

      // Send the coordinates upwards through the offsetParent chain.
      var e = el;
      while (e) {
        e.mouseX = pos.x;
        e.mouseY = pos.y;
        pos.x += e.offsetLeft;
        pos.y += e.offsetTop;
        e = e.offsetParent;
      }

      // Look for the coordinates starting from the wheel widget.
      var e = reference;
      var offset = { x: 0, y: 0 }
      while (e) {
        if (typeof e.mouseX != 'undefined') {
          x = e.mouseX - offset.x;
          y = e.mouseY - offset.y;
          break;
        }
        offset.x += e.offsetLeft;
        offset.y += e.offsetTop;
        e = e.offsetParent;
      }

      // Reset stored coordinates
      e = el;
      while (e) {
        e.mouseX = undefined;
        e.mouseY = undefined;
        e = e.offsetParent;
      }
    }
    else {
      // Use absolute coordinates
      var pos = self.absolutePosition(reference);
      x = (event.pageX || 0*(event.clientX + document.documentElement.scrollLeft)) - pos.x;
      y = (event.pageY || 0*(event.clientY + document.documentElement.scrollTop)) - pos.y;
    }
    // Subtract distance to middle
    return { x: x - self.width / 2, y: y - self.width / 2 };
  }

  /**
   * Mousedown handler
   */
  self.mousedown = function (event) {
    // Capture mouse
    if (!document.dragging) {
      document.documentElement.addEventListener('mousemove', self.mousemove);
      document.documentElement.addEventListener('mouseup', self.mouseup);
      document.dragging = true;
    }

    // Check which area is being dragged
    var pos = self.widgetCoords(event);
    self.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > self.square;

    // Process
    self.mousemove(event);
    return false;
  }

  /**
   * Mousemove handler
   */
  self.mousemove = function (event) {
    // Get coordinates relative to color picker center
    var pos = self.widgetCoords(event);

    // Set new HSL parameters
    if (self.circleDrag) {
      var hue = Math.atan2(pos.x, -pos.y) / 6.28;
      if (hue < 0) hue += 1;
      self.setHSL([hue, self.hsl[1], self.hsl[2]]);
    }
    else {
      var sat = Math.max(0, Math.min(1, -(pos.x / self.square) + .5));
      var lum = Math.max(0, Math.min(1, -(pos.y / self.square) + .5));
      self.setHSL([self.hsl[0], sat, lum]);
    }
    return false;
  }

  /**
   * Mouseup handler
   */
  self.mouseup = function () {
    // Uncapture mouse
    document.documentElement.removeEventListener('mousemove', self.mousemove);
    document.documentElement.removeEventListener('mouseup', self.mouseup);
    document.dragging = false;
  }

  /**
   * Update the markers and styles
   */
  self.updateDisplay = function () {
    // Markers
    var angle = self.hsl[0] * 6.28;
    document.querySelector('.h-marker').style.left = Math.round(Math.sin(angle) * self.radius + self.width / 2) + 'px';
    document.querySelector('.h-marker').style.top = Math.round(-Math.cos(angle) * self.radius + self.width / 2) + 'px';

    document.querySelector('.sl-marker').style.left = Math.round(self.square * (.5 - self.hsl[1]) + self.width / 2) + 'px';
    document.querySelector('.sl-marker').style.top = Math.round(self.square * (.5 - self.hsl[2]) + self.width / 2) + 'px';

    // Saturation/Luminance gradient
    document.querySelector('.color').style.backgroundColor = self.pack(self.HSLToRGB([self.hsl[0], 1, 0.5]));

    
    // Linked elements or callback
    if (typeof self.callback == 'object') {
      // Set background/foreground color
      self.callback.style.backgroundColor = self.color;
      self.callback.style.color = self.hsl[2] > 0.5 ? '#000' : '#fff';

      // Change linked value
      if (self.callback.value && self.callback.value != self.color) {
        self.callback.value = self.color;
      }
    }
    else if (typeof self.callback == 'function') {
      self.callback.call(self, self.color);
    }
  }

  /**
   * Get absolute position of element
   */
  self.absolutePosition = function (el) {
    var r = { x: el.offsetLeft, y: el.offsetTop };
    // Resolve relative to offsetParent
    if (el.offsetParent) {
      var tmp = self.absolutePosition(el.offsetParent);
      r.x += tmp.x;
      r.y += tmp.y;
    }
    return r;
  };

  /* Various color utility functions */
  self.pack = function (rgb) {
    var r = Math.round(rgb[0] * 255);
    var g = Math.round(rgb[1] * 255);
    var b = Math.round(rgb[2] * 255);
    return '#' + (r < 16 ? '0' : '') + r.toString(16) +
           (g < 16 ? '0' : '') + g.toString(16) +
           (b < 16 ? '0' : '') + b.toString(16);
  }

  self.unpack = function (color) {
    if (color.length == 7) {
      return [parseInt('0x' + color.substring(1, 3)) / 255,
        parseInt('0x' + color.substring(3, 5)) / 255,
        parseInt('0x' + color.substring(5, 7)) / 255];
    }
    else if (color.length == 4) {
      return [parseInt('0x' + color.substring(1, 2)) / 15,
        parseInt('0x' + color.substring(2, 3)) / 15,
        parseInt('0x' + color.substring(3, 4)) / 15];
    }
  }

  self.HSLToRGB = function (hsl) {
    var m1, m2, r, g, b;
    var h = hsl[0], s = hsl[1], l = hsl[2];
    m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
    m1 = l * 2 - m2;
    return [this.hueToRGB(m1, m2, h+0.33333),
        this.hueToRGB(m1, m2, h),
        this.hueToRGB(m1, m2, h-0.33333)];
  }

  self.hueToRGB = function (m1, m2, h) {
    h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
    if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
    if (h * 2 < 1) return m2;
    if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
    return m1;
  }

  self.RGBToHSL = function (rgb) {
    var min, max, delta, h, s, l;
    var r = rgb[0], g = rgb[1], b = rgb[2];
    min = Math.min(r, Math.min(g, b));
    max = Math.max(r, Math.max(g, b));
    delta = max - min;
    l = (min + max) / 2;
    s = 0;
    if (l > 0 && l < 1) {
      s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
    }
    h = 0;
    if (delta > 0) {
      if (max == r && max != g) h += (g - b) / delta;
      if (max == g && max != b) h += (2 + (b - r) / delta);
      if (max == b && max != r) h += (4 + (r - g) / delta);
      h /= 6;
    }
    return [h, s, l];
  }

  // Install mousedown handler (the others are set on the document on-demand)
  //$('*', e).mousedown(self.mousedown);
  container.addEventListener("mousedown",self.mousedown);

    // Init color
  self.setColor('#000000');

  // Set linked elements/callback
  if (callback) {
    self.linkTo(callback);
  }
}